//
//  HeaderWebView.m
//  Traveling
//
//  Created by 尹桥印 on 15/6/10.
//  Copyright (c) 2015年 长沙市岳麓区立早网络科技有限公司. All rights reserved.
//

#import "HeaderWebView.h"

@interface HeaderWebView()

@property (nonatomic, weak) UIWebView *webView;

@end
@implementation HeaderWebView

@dynamic delegate;

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        UIWebView *webView =  [[UIWebView alloc] init];
        [self addSubview:webView];
        self.webView = webView;
        [self addKVO];
        
    }
    return self;
}

-(void)addKVO{
    UIScrollView *scrollview = [[self.webView subviews]firstObject];
    [scrollview addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];

}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    if([keyPath isEqualToString:@"contentSize"]){
        NSValue *oldSize = [change objectForKey:@"old"];
        NSValue *newSize = [change objectForKey:@"new"];
        if ([oldSize CGSizeValue].height!=[newSize CGSizeValue].height) {
            [self.webView setHeight:[newSize CGSizeValue].height];
            [self setContentSize:CGSizeMake(self.width, CGRectGetMaxY(self.webView.frame))];
        }
    }
}

-(void)setHeaderView:(UIView *)headerView{
    _headerView = headerView;
    [self addSubview:headerView];
    self.webView.height = self.height-headerView.height;
}

-(void)setUrl:(NSString *)url{
    _url = url;
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
}

-(void)layoutSubviews{
    [super layoutSubviews];
    self.headerView.width = self.width;
    self.webView.y = CGRectGetMaxY(self.headerView.frame);
    self.webView.width = self.width;
}

-(void)dealloc{
    UIScrollView *scrollview = [[self.webView subviews]firstObject];
    [scrollview removeObserver:self forKeyPath:@"contentSize"];
}

@end
